package com.lx.mobileplayer.net

import com.google.gson.Gson
import com.lx.mobileplayer.app.MyApplication
import com.lx.mobileplayer.utils.LogUtil
import okhttp3.*
import java.io.IOException
import java.lang.reflect.ParameterizedType

/**
 * 类说明：网络请求的工具类
 * Created by liuxiong on 2019/4/26.
 */
class OkHttpUtil private constructor(){

    companion object {
        val instance by lazy{
            OkHttpUtil()
        }
    }

    private lateinit var gson:Gson
    private lateinit var client:OkHttpClient

    init {
        gson=Gson()
        client=OkHttpClient()
    }

    fun <T> request(url:String,callback:ResultCallBack<T>){

        var request= Request.Builder().url(url).get().build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {

                MyApplication.uiHandler.post {
                    callback.failed(-1,e.toString())
                }
            }

            override fun onResponse(call: Call, response: Response) {

                response.code()
                var result=response.body()?.string()
                LogUtil.d(result)

                //获取泛型类型
                var type=(callback.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]

                var data:T?=null
                try {
                    data=gson.fromJson<T>(result,type)
                }catch (e:Exception){
                    LogUtil.d("Gson解析失败")
                }

                MyApplication.uiHandler.post {
                    if(data==null){
                        callback.failed(-2,"Gson解析失败")

                    }else{
                        callback.succecss(data)
                    }
                }
            }
        })

    }

    abstract class ResultCallBack<T>{
        abstract fun failed(code:Int,errorMessage:String)
        abstract fun succecss(data:T)
    }
}